#!/bin/bash

# Step 1: Preinstallation
echo "Starting preinstallation..."
curl -fsSL https://get.docker.com -o get-docker.sh
sh get-docker.sh
mv ../ctfd-owhale/ ../CTFd/

# Step 2: Install frps
echo "Installing frps..."
cd ~
wget https://github.com/fatedier/frp/releases/download/v0.56.0/frp_0.56.0_linux_amd64.tar.gz
tar -zxvf frp_0.56.0_linux_amd64.tar.gz
cd frp_0.56.0_linux_amd64
sudo mkdir /etc/frp
sudo cp frpc.toml frps.toml /etc/frp/
sudo cp frpc frps /usr/bin/
sudo chmod a+x /usr/bin/frpc /usr/bin/frps

# Set frps.toml config
echo "Setting frps.toml config..."
sudo bash -c 'cat <<EOF > /etc/frp/frps.toml
bindAddr = "0.0.0.0"
bindPort = 7897
auth.method = "token"
auth.token = "token"
vhostHTTPPort = 8080
subDomainHost = "127.0.0.1.xip.io"
log.to = "./frps.log"
log.level = "info"
EOF'

# Create frps service
echo "Creating frps service..."
sudo bash -c 'cat <<EOF > /etc/systemd/system/CTFd-Frps.service
[Unit]
Description=CTFd Dedicated Frp Server
After=network.target

[Service]
Type=simple
User=nobody
Restart=on-failure
RestartSec=5s
ExecStart=/usr/bin/frps -c /etc/frp/frps.toml

[Install]
WantedBy=multi-user.target
EOF'

# Restart frps service
echo "Restarting frps service..."
sudo systemctl enable CTFd-Frps
sudo systemctl start CTFd-Frps

# Step 3: Docker network
echo "Setting up Docker network..."
cd ~/CTFd/
docker swarm init
docker node update --label-add "name=linux-1" $(docker node ls -q)

# Step 4: frpc (client) configuration
echo "Configuring frpc (client)..."
mkdir -p ./conf/frp
mkdir -p ./conf/compose-frp

cat <<EOF > ./conf/frp/frpc.ini
[common]
token="token"
server_addr = "172.17.0.1"
server_port = 7897
admin_addr = "172.1.0.4"
admin_port = 7400
EOF

cat <<EOF > ./conf/compose-frp/frpc.ini
[common]
token="token"
server_addr = "172.17.0.1"
server_port = 7897
admin_addr = "172.1.0.5"
admin_port = 7400
EOF

# Step 5: Docker-compose up
echo "Starting Docker compose..."
chmod +x docker-entrypoint.sh
sudo docker compose build
sudo docker compose up -d

echo "Script execution completed."
